import api from '../../../api/index';
import dayjs from '../../../plugin/dayjs/index';
import daysbefore from '../../../plugin/daysbefore';
import * as echarts from '../../../components/ec-canvas/echarts';
const lsPlugin = requirePlugin("lzbluetooth");


//全局声明chart
var seriesDataArr = [];
var timeArr = [];
var chart = null;

// 时间格式化
function formatTime(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
}
function formatDatelx (timestamp) {
	const date = new Date(timestamp * 1000);
	const year = date.getFullYear();
	const month = (date.getMonth() + 1).toString().padStart(2, '0');
	const day = date.getDate().toString().padStart(2, '0');
	const hours = date.getHours().toString().padStart(2, '0');
	const minutes = date.getMinutes().toString().padStart(2, '0');
	const seconds = date.getSeconds().toString().padStart(2, '0');
  
	return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }
function formatTime2(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD');
}
Page({
	/**
   * 页面的初始数据
   */
	data: {
		showDialogdevice: false,
		inputshow: false,
		inputshow2: false,
		inputlist2: [{ unit: '步', value: '', text: '请输入目标步数' }],
		inputlist: [{ unit: '步', value: '', text: '请输入步数' }, { unit: 'kcal', value: '', text: '请输入能耗' }],
		shebeiicon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/sportsAdministration/shouhuan.png',
		fasleshebeiicon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/sportsAdministration/gantanhao.png',
		targetSteps: '--',
		percentValue: 0,  //百分比
		kcalValue: '--',
		linedata: null,
		show: false,
		showecharts: false,
		ec: {
			// 初始化图表
			onInit: (canvas, width, height) => {
				//初始化echarts元素，绑定到全局变量，方便更改数据
				chart = echarts.init(canvas, null, {
					width: width,
					height: height
				});
				canvas.setChart(chart);
				return chart;
			}
		},
		currentDevice: null,
		bindDevice: null,
		timer: null,
		bleAvaible: true,
		showDialog: false,
		bindDeviceTextInfo: '',
		step: 0,   //步数
	},

	/**
   * 生命周期函数--监听页面加载
   */
	onLoad(options) {
		// this.drawProgress()
		const { titlename } = options
		console.log(titlename);
		wx.setNavigationBarTitle({
		  title: titlename // 设置页面标题
		})
		this.gettoken()
		this.gethistrorylist(); //查看历史数据
		this.getloadlist(); //查询当前最新数据
		this.gettargetSteps()
	},
		/**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
	// var that = this;
	// that.canvasRing = that.selectComponent('#canvasRing');
	// that.canvasRing.showCanvasRing();
},

/**
* 生命周期函数--监听页面显示
*/
onShow() {
	wx.openBluetoothAdapter({
		success: (res) => {
			console.log('蓝牙功能已开启！')
			this.initPlugin()
			setTimeout(() => {
				console.log('走了这里--------000--------');
				this.getDeviceList()
			}, 500);
		},
		fail: () =>  {
			console.log('走了这里--------222--------');
			this.setData({
				bindDeviceTextInfo: '蓝牙未开启，请开启蓝牙'
			})
			this.setData({
				showDialog: true
			})
			this.jianting()
			}
		})
 },
	onDevice() {
		wx.openBluetoothAdapter({
			success: (res) => {
				console.log('蓝牙功能已开启！')
				this.initPlugin()
				setTimeout(() => {
					console.log('走了这里--------000--------');
					this.getDeviceList()
				}, 500);
			},
			fail: () =>  {
				console.log('走了这里--------222--------');
				this.setData({
					bindDeviceTextInfo: '蓝牙未开启，请开启蓝牙'
				})
				this.setData({
					showDialog: true
				})
				this.jianting()
				}
			})
	},
	gettoken() {
		try {
			api.get(`/api/hxhealth/sghealth/token`).then((res) => {
				console.log(res);
				this.getsign()
			});
		} catch (e) {
			console.error(e);
		}
	},
	getsign() {
		try {
			api.get(`/api/hxhealth/sghealth/sign`).then((res) => {
				console.log(res);
				let appKeys = res[0].appKey
				let sign = res[0].sign
				let timestamp = res[0].timestamp
				// this.gosanfang(sign,appKeys,timestamp)   //h5页面
				this.setData({
					sign,
					appKeys,
					timestamp
				})
				// this.bushupush()
			});
		} catch (e) {
			console.error(e);
		}
	},
	jianting() {
		var that = this
		// 监听蓝牙适配器状态变化
		wx.onBluetoothAdapterStateChange((res) => {
			if (res.available) {
			  // 蓝牙已经开启
			  that.initPlugin();
			  setTimeout(() => {
				  console.log('走了这里--------111--------');
				  this.setData({
					showDialog: false
				})
					that.getDeviceList()
				}, 500);
			}
		});
	},
	//查看已绑定设备列表
	async getDeviceList() {
		const res = await api.post('/api/user/storage/get', {
			data: {
				'key': 'devicelist'
			}
		})
		if (res[0].value) {
			var array = JSON.parse(res[0].value)
			const listValue = array.filter(item => item.name === 'bracelet')
			console.log(listValue);
			if (listValue.length > 0) { // 如果绑定的有设备，直接连接
				if (listValue[0].devicelist.length > 0) {
					this.setData({
						currentDevice: listValue[0].devicelist[0]
					})
					this.onBind()
				} else {
					this.setData({
						showDialogdevice: true
					})
				}
			} else {
				this.setData({
					showDialogdevice: true
				})
			}
		}
	},
	getWeekDays() {
		let dates = []
		for (var i = 365; i >= 0; i--) {
			var currentDate = new Date();
			currentDate.setDate(currentDate.getDate() - i);
			var month = ("0" + (currentDate.getMonth() + 1)).slice(-2);
			var day = ("0" + currentDate.getDate()).slice(-2);
			var formattedDate = month + "/" + day;
			dates.push(formattedDate);
		}
		return dates
	},
	gethistrorylist() {
		api
			.post('/api/hxhealth/exams/records', {
				data: {
					everyday: true,
					itemcode: 'lk1591234989246',
					typecode: 'wriststrap',
					everyday: true
				},
				head: {
					firstresult: 0,
					maxresults: 1000,
					bodytype: 'flat',
				}
			})
			.then((res) => {
				// console.log(res);
				console.log('----历史数据----', res);
				if (res.length > 0) {
					const jsonData = res;
					// 提取数据的数组
					const values = [];
					const times = [];

					// 遍历 body 数组
					jsonData.forEach((entry) => {
						// 遍历 devices 数组
						entry.devices.forEach((device) => {
							console.log(device);
							// 找到 code 为 "lk1591234989246" 的项
							const item = device.items.find((item) => item.code === 'lk1591234989246');

							// 如果找到了，将 value 和 time 添加到相应的数组中
							if (item) {
								console.log(item);
								values.push(Number(item.value)); // 将值转换为数字类型
								times.push(entry.time.slice(0, 10).replace(/-/g, '/'));
							}
						});
					});
					const linedata = {
						values,
						times
					};
					console.log(linedata);
					this.setData({
						linedata
					});
					// 模拟获取接口数据
					setTimeout(() => {
						this.getEchartData(linedata);
					}, 1000);
				} else {
					const linedata = {
						values: [],
						times: this.getWeekDays()
					};
					this.setData({
						linedata
					});
					// 模拟获取接口数据
					setTimeout(() => {
						this.getEchartData(linedata);
					}, 1000);
				}
			});
	},
	getloadlist() {
		// 整体列表查询
		api
			.post('/api/exams/lastvalues', {
				data: {
					devkind: 'wriststrap',
					devmode: '',
					itemcode: '',
					typecode: '',
					unionuser: true
				}
			})
			.then((res) => {
				// console.log(res);
				console.log('----最新数据----', res);
				const array = res;
				for (let y = 0; y < array.length; y++) {
					if (array[y].code == 'XYZBQT02') {
						console.log(array[y].value);
						this.setData({
							kcalValue: Number(array[y].value).toFixed(0)
						});
					}
					if (array[y].code == 'lk1591234989246') {
						this.setData({
							step: array[y].value,
						});
					}
				}
			});
	},
	gettargetSteps() {
		console.log('777', this.data.targetSteps);
		let data = {
			"value": this.data.inputlist2[0].value,
			"key": "targetSteps"
		};
		// 目标步数保存
		api
			.post('/api/user/storage/get', {
				data
			})
			.then((res) => {
				this.setData({
					targetSteps: res[0].value?res[0].value:'--'
				});
				console.log(res);
				console.log('----查询目标步数----', res);
			});
	},
	savedevices2() {
		if (this.data.inputlist2[0]) {
			console.log('666', this.data.inputlist2[0]);
			let data = {
				"value": this.data.inputlist2[0].value,
				"key": "targetSteps"
			};
			// 目标步数保存
			api
				.post('/api/user/storage/set', {
					data
				})
				.then((res) => {
					// console.log(res);
					console.log('----保存录入----', res);
					this.getloadlist();
					this.closesaveNickname();
					this.gettargetSteps()
					// wx.showToast({
					// 	icon: 'none',
					// 	title: '保存成功'
					// });
					this.setData({
						inputshow2: false,
						'inputlist2[0].value': ''
					});
				})
				.catch((e) => {
					console.log(e);
					wx.showToast({
						icon: 'none',
						title: e.faultstring ? e.faultstring : '保存失败'
					});
				});
		}

	},
	savedevices(result,resultkcal) {
		if( result && resultkcal ) {
		let data = {
			name: '运动监测',
			time: formatTime(),
			typecode: 'wriststrap',
			typename: '运动监测',
			devices: [
				{
					name: '运动监测',
					kind: 'wriststrap',
					items: [
						{
							code: 'lk1591234989246',
							checkDate: null,
							level: null,
							value: result,
							deviceBrand: '',
							deviceNo: ''
						},
						{
							code: 'XYZBQT02',
							checkDate: null,
							level: null,
							value: resultkcal,
							deviceBrand: '',
							deviceNo: ''
						}
					]
				}
			]
		};
		this.save(data)
		} else {
			let data = {
				name: '运动监测',
				time: formatTime(),
				typecode: 'wriststrap',
				typename: '运动监测',
				devices: [
					{
						name: '运动监测',
						kind: 'wriststrap',
						items: [
							{
								code: 'lk1591234989246',
								checkDate: null,
								level: null,
								value: result,
								deviceBrand: '',
								deviceNo: ''
							}
						]
					}
				]
			};
			this.save(data)
		}
		
	},
	save(data) {
		// 整体列表保存
		api
			.post('/api/hxhealth/exams/save', {
				data
			})
			.then((res) => {
				// console.log(res);
				console.log('----保存录入----', res);
				this.getloadlist();
				this.closesaveNickname();
				// wx.showToast({
				// 	icon: 'none',
				// 	title: '保存成功'
				// });
			})
			.catch((e) => {
				console.log(e);
				wx.showToast({
					icon: 'none',
					title: e.faultstring ? e.faultstring : '保存失败'
				});
			});
	},
	openNickname() {
		this.setData({
			inputshow: true
		});
	},
	openNickname2() {
		this.setData({
			inputshow2: true
		});
	},
	closesaveNickname() {
		this.setData({
			inputshow: false
		});
	},
	closesaveNickname2() {
		this.setData({
			inputshow2: false
		});
	},
	userNameInput1(e) {
		this.setData({
			'inputlist[0].value': e.detail.value
		});
	},
	userNameInput2(e) {
		console.log(e.detail.value);
		this.setData({
			'inputlist2[0].value': e.detail.value
		});
	},
	saveNickname() {
		if(!/^[1-9]\d*$/.test(this.data.inputlist[0].value)) {
			wx.showToast({
				title: '请输入正整数',
				icon: 'none',
				duration: 2000
			})
			return
		}
		this.savedevices(this.data.inputlist[0].value);
	},
	saveNickname2() {
		console.log(this.data.inputlist2);
		this.savedevices2();
	},
	modal_click_Hidden() {
		this.setData({
			inputshow: false
		});
	},
	// 绘制图表
	runColumncCanva() {
		var option = {
			title: {
				// text: '次/分',
				textStyle: {
					fontSize: 9,
					color: '#666666'
				}
			},
			color: ['#37A2DA'],
			legend: {
				data: ['运动监测变化趋势'],
				icon: 'circle',
				left: 0,
				itemWidth: 9,
				// itemStyle: {
				//     color: '#5BBF70'
				// },
				textStyle: {
					color: '#333333',
					fontSize: 16
				}
			},
			grid: {
				left: '0%',
				right: '5%',
				bottom: 0,
				top: '15%',
				containLabel: true,
				show: true
			},

			tooltip: {
				show: true,
				trigger: 'axis'
			},
			xAxis: {
				type: 'category',
				boundaryGap: false,
				data: timeArr,
				axisLabel: {
					fontSize: 16,
					rotate: 0 //倾斜度 -90 至 90 默认为0
				}
			},
			yAxis: {
				type: 'value',
				splitLine: {
					lineStyle: {
						type: 'dashed'
					}
				},
				axisLabel: {
					fontSize: 16
				}
			},
			series: seriesDataArr
		};
		//这里一定要做个charts是否存在的判断，因为万一ec那里没有初始化，这里就会报错
		if (chart) {
			chart.setOption(option);
			this.setData({
				show: true
			});
		}
	},
	getEchartData(linedata) {
		seriesDataArr = [
			{
				name: '运动监测变化趋势',
				type: 'line',
				stack: 'Total',
				smooth: true,
				data: linedata.values
			}
		];
		timeArr = linedata.times;
		this.runColumncCanva();
	},
	// 初始化插件
	initPlugin() {
		lsPlugin.init({
			appId: "lx758d9d23a6bac221",
			logger: null,
			// 微信蓝牙开关回调
			onBluetoothAdapterStateChange: (res) => {
				console.log(res, 'BBBBB')
				if (res.available) {
					console.log('手环插件初始化成功')
					this.setData({
						bleAvaible: true
					})
					wx.offBluetoothAdapterStateChange()	
				} else {
					this.setData({
						bleAvaible: false
					})
					console.log(res, '手环插件初始化失败')
				}
			},
		})
	},
	onCancel() {
		this.setData({
			showDialog: false,
		})
		// 停止搜索
		this.stopScan()
	},
	// 扫码设备
	onScan() {
		console.warn('--------------', '扫描')
		lsPlugin.startScanning(device => {
			console.warn('发现设备', device)
			// 判断是否存在A5
			if (device.name.indexOf('HR6') > -1) {
				console.warn('发现HR6设备', device)
				this.setData({
					currentDevice: device
				})
				this.onBind(device)
			} else {
				this.setData({
					bindDeviceTextInfo: '未发现对应的设备'
				})
				setTimeout(() => {
					this.setData({
						showDialog: false,
					})
				}, 500);
			}
			//  // 记录扫描到的设备
			//  const find = this.data.devices.find((item) => item.deviceId === device.deviceId)
			// 	if (typeof find === "undefined") {
			// 		 return this.data.devices.concat(device)
			// 	} else {
			// 		 return this.data.devices
			// 	}
		})
	},
	// 未发现绑定，5秒再扫描一次
	createTimeInter() {
		this.data.timer = setInterval(() => {
			if (!this.data.currentDevice) {
				this.onScan()
			} else {
				this.stopScan()
			}
		}, 5000)
	},
	// 停止扫描
	stopScan() {
		lsPlugin.stopScanning();
	},
	// 解绑设备
	doDeleteMonitorDevice() {
		lsPlugin.deleteMonitorDevice({
			mac: this.data.currentDevice.mac,
		})
	},
	// 添加监听
	doAddMonitorDevice(device) {
		console.log(this.data.currentDevice, 'AAAAAAAAAAAAA')
		let _device = device ? device : this.data.currentDevice
		lsPlugin.addMonitorDevice({
			mac: _device.mac,
			model: _device.model,
		})
	},
	// 添加监听
	onBind(device) {
		return new Promise((resolve, reject) => {
			this.setData({
				bindDeviceTextInfo: '设备链接中'
			})
			this.setData({
				showDialog: true
			})
			this.stopScan()
			// 防止嵌套的缓存问题
			let _device = device ? device : this.data.currentDevice
			this.setData({
				currentDevice: _device
			})
			console.log(_device, '--------------开始绑定设备')
			if (_device) {
				console.warn('--------------开始绑定设备')
				// 如果是安卓设备，则需要判断位置是否可用，位置权限是否可用 let { locationEnabled, locationAuthorized } = wx.getSystemInfoSync();
				lsPlugin.bindDevice({
					mac: _device.mac,
					callback: res => {
						console.warn('绑定设备结束', res)
						// 绑定成功
						if (res.bindState === 4) {
							const bindDevice = {
								mac: res.mac,
								bindState: res.bindState,
								model: _device.model,
								localName: _device.localName,
							}
							this.setData({
								bindDevice: bindDevice
							})
							// 监听数据
							console.warn('开始监听数据')
							this.onDataReport()
							this.doAddMonitorDevice()
							this.setData({
								bindDeviceTextInfo: '设备绑定成功'
							})
							resolve()
							// setTimeout(() => {
							// 	this.setData({
							// 		showDialog: false,
							// 	})
							// }, 1500);
							// 绑定失败
						} else if (res.bindState) {
							console.log('绑定失败',res.bindState)
							this.setData({
								bindDeviceTextInfo: '设备绑定中'
							})
							reject()
							// setTimeout(() => {
							// 	this.setData({
							// 		showDialog: false,
							// 	})
							// }, 1500);
						} else if (res?.errorCode) {
							console.log('绑定失败')
							this.setData({
								bindDeviceTextInfo: '设备绑定失败'
							})
							reject()
							// setTimeout(() => {
							// 	this.setData({
							// 		showDialog: false,
							// 	})
							// }, 1500);
						} else {
							this.setData({
								bindDeviceTextInfo: '设备绑定失败'
							})
							reject()
							// setTimeout(() => {
							// 	this.setData({
							// 		showDialog: false,
							// 	})
							// }, 1500);
						}
					}
				});
			} else {
				// showToast({title: "绑定失败，设备断开", icon: 'none'});
			}
		})
	},
	// 监听数据上报
	onDataReport() {
		console.log('监听数据开始')
		lsPlugin.$on({
			eventName: "dataReport",
			eventKey: 'wo',  // 唯一标识，同一标识的监听会被覆盖
			callback: (device, data) => {
				console.log(device);
				this.setData({
					lzDeviceId: device.lzDeviceId, 
				})
				// const sportMode10 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
				const arr = ["a5Daily", "a5HR", "a5Sleep", 'a5SportCalories', 'a5SportReport', 'bloodOxygen', 'a5SportStatus', 'sleepReport']
				// https://mp.weixin.qq.com/wxopen/plugindevdoc?appid=wxe3d2a6ab8dd5b49b&token=1156697109&lang=zh_CN
				if (!!data?.dataType && arr.indexOf(data?.dataType) > -1) {
					console.log(data, '收到数据了')
					// this.recursiveApiCall(16,30)
					// this.shuimianpush()
					this.setData({
						bindDeviceTextInfo: '正在更新数据'
					})
					this.setData({
						showDialog: true,
					})
					setTimeout(() => {
						this.setData({
							bindDeviceTextInfo: '数据已更新'
						})
							}, 2500);
					setTimeout(() => {
						this.setData({
							showDialog: false,
						})
					}, 4000);
					
					if (data.dataType === 'a5Daily') {
						if (data.list && data.list.length > 0) {
							console.log(data.list[0]);
							this.setData({
								step: data.list[0].step, //步数
								kcalValue: data.list[0].calories.toFixed(0), //卡路里
								distance: data.list[0].distance, //距离米
								examount: data.list[0].examount, //运动量
								exerciseTime: data.list[0].exerciseTime, //运动时间
								silenceHeartRate: data.list[0].silenceHeartRate, //静息心率
								utc: formatDatelx(data.list[0].utc) //测量时间
								
							})
							console.log('上传步数数据了------000-------')
							this.bushupush(data.list[0].utc)
							const perc = Math.round(data.list[0].step / Number(this.data.targetSteps)).toFixed(2)
							if(this.data.step!==0) {
								this.savedevices(this.data.step,this.data.kcalValue)
							}
							console.log(perc, 'percpercperc')
							this.setData({
								percentValue: perc * 100,
								showecharts: true
							})
						}
					}
					if (data.dataType === 'a5HR') {
						console.log(data, '收到心率数据了---111---')
						console.log(data);
						if (data.heartRates && data.heartRates.length > 0) {
							this.xinlvpush(data.utc,data.heartRates[0],data.heartRates.length)
						}
					}
					if(data.dataType === 'a5Sleep') {
						console.log(data, '收到睡眠据了---222---')
						console.log(data);
					}
					if(data.dataType === 'a5SportCalories') {
						console.log(data, '收到运动卡路里数据了--333----')
						console.log(data);
					}
					if(data.dataType === 'a5SportReport') {
						console.log(data, '收到运动报告数据了--444----')
						console.log(data);
						// (1,"跑步"), //户外跑步
						// (2,"健走"),//户外健走
						// (3,"骑行"),
						// (4,"游泳"),
						// (5,"健身"),
						// (6,"篮球"),
						// (7,"足球"),
						// (8,"羽毛球"),
						// (9,"排球"),
						// (10,"乒乓球"),
						// (11,"瑜伽"),
						// (12,"电竞"),
						// (15,"室内跑"),//室内跑步
						// (16,"椭圆机"),
						// (19,"健身操"),
						// (20,"打太极"),
						// (21,"力量训练"),
						// (22,"室内骑行"),
						// (23,"划船机"),
						// (24,"自由训练")
						const list = [{old:1,newnum:1},{old:2,newnum:2},{old:3,newnum:3},{old:10,newnum:6},{old:11,newnum:7},{old:12,newnum:8},{old:14,newnum:10},{old:15,newnum:11},{old:7,newnum:15},{old:8,newnum:16},{old:5,newnum:21},{old:24,newnum:22},{old:22,newnum:23},{old:25,newnum:24}]
						var result = null;
						for (var i = 0; i < list.length; i++) {
							if (list[i].old === data.sportMode) {
							  result = list[i].newnum;
							  break;
							}
						  }
						console.log(result);
						this.setData({
							ydavgHr: data.avgHr, //平均心率
							ydavgPace: data.avgPace, //平均配速
							ydavgSpeed: data.avgStepFreq, //平均速度
							ydavgStepRate: data.avgStepOfFloating, //平均步频
							ydcalories: data.calories, //总卡路里
							yddistance: data.distance, //总里程
							ydendTime:  data.end* 1000, //结束时间
							ydexerciseTime: data.sportTime, //运动时长
							ydexerciseType: result, //锻炼类型
							ydmaxHeartRate: data.maxHr, //最大心率
							ydstartTime: data.start* 1000, //开始时间
							ydstep: data.step //总步数，当锻炼类型为4时代表趟数
						})
						this.yundongpush()
						 
					}
					if(data.dataType === 'bloodOxygen') {
						console.log(data, '收到血氧数据了--555----')
						console.log(data);
					}
					if(data.dataType === 'a5SportStatus') {
						console.log(data, '收到运动状态数据了--666----')
						console.log(data);
					}
					if(data.dataType === 'sleepReport') {
						console.log(data, '收到睡眠报告状态数据了--------7777-----------------')
						console.log(data);
						let list = []
						let items = {}
						const userInfo = wx.getStorageSync('userInfo')
						items.awakeDuration = data.durationOfAwake
						items.awakeningTime = data.awakeUtc *1000
						items.deepSleepDuration = data.timeOfDeepSleep
						items.deviceId = this.data.lzDeviceId
						items.lightSleepDuration = data.timeOfLightSleep
						items.measurementTime = data.sleepUtc*1000
						items.remDuration = data.numberOfEyeMovement
						items.sleepScore = 0
						items.sleepTime = data.sleepUtc*1000
						items.startSleepDuration = 0
						items.userId = userInfo.id
						let inputArray = data.sleepList;
						let outputArray = inputArray.map(item => ({
							sleepStatus: item.deep,
							duration: item.duration,
							endTime: item.endUtc * 1000,
							startTime: item.startUtc * 1000
						  }));
						items.sleepDetailList = outputArray
						list.push(items)
						this.shuimianpush(list)
					}
					
					// 记录最后一次收到的测试数据
					// setCurrentTestData(data)
				}
				// 记录所有收到的测试数据
				// setTestData(testData => testData.concat(data))
			},
		});
	},
	// recursiveApiCall(value, count) {
	// 	if (count <= 0) {
	// 	  return;
	// 	}
	  
	// 	// 调用接口，并传入值
	// 	this.yundongpush(value);
	  
	// 	// 递归调用函数，传入值加1，并减少count
	// 	this.recursiveApiCall(value + 1, count - 1);
	//   },
		// 运动数据上传
		yundongpush(){
			console.log('jinlailema--------运动数据-----',this.data.appKeys);
			const userInfo = wx.getStorageSync('userInfo')
			var that = this
			wx.request({
				url: `https://api.leshiguang.com/api/exercise/v2.0/upload/uploadDeviceExerciseRecord?api_sign=${this.data.sign}&api_appKey=${this.data.appKeys}&api_version=1.0&api_timestamp=${this.data.timestamp}`,
				method: 'POST', // 请求方法为POST
				data: {
					"associatedId": userInfo.id,
					"list": [
					  {
						// "dataType":3,
						// "avgHeartRate":79,
						// "avgPace":0,
						// "avgSpeed":0,
						// "avgStepRate":0,
						// "calories":0,
						// "dataSource":1,
						// "deviceId":"3a040500a557",
						// "distance":0,
						// "endTime":1715010747000,
						// "exerciseTime":130,
						// "exerciseType": value,
						// "maxHeartRate":87,
						// "startTime":1715009967000,
						// "step":0
						dataType: 2,
						"avgHeartRate": that.data.ydavgHr,   //平均心率
       					"avgPace": that.data.ydavgPace,  //平均配速
       					"avgSpeed": that.data.ydavgSpeed, //平均速度
       					"avgStepRate": that.data.ydavgStepRate, //平均步频
       					// "bestSpeed": 0, //最大速度 
       					"calories": that.data.ydcalories, //总卡路里
       					"dataSource": 1,  //数据来源 
       					"deviceId": that.data.lzDeviceId,
       					"distance": that.data.yddistance, //总里程
       					"endTime": that.data.ydendTime,  //结束时间
       					"exerciseTime": that.data.ydexerciseTime, //运动时长
       					"exerciseType": that.data.ydexerciseType, //锻炼类型
       					"maxHeartRate": that.data.ydmaxHeartRate, //最大心率
       					// "maxStepRate": 0, //最大步频
       					"startTime": that.data.ydstartTime,  //开始时间
						"step": that.data.ydstep  //总步数，当锻炼类型为4时代表趟数
					  }
					]
				},
				header: {
				 'associatedId': userInfo.id,
				  'content-type': 'application/json' // 设置请求头为JSON格式
				},
				success: function(res) {
				  // 请求成功的回调函数
				  console.log(userInfo.id);
				 
				},
				fail: function(res) {
				  // 请求失败的回调函数
				  console.log(res.errMsg);
				}
			  });
		},
		// 步数数据上传
		bushupush(utc){
			// step: data.list[0].step, //步数
			// kcalValue: data.list[0].calories.toFixed(0), //卡路里
			// distance: data.list[0].distance, //距离米
			// examount: data.list[0].examount, //运动量
			// exerciseTime: data.list[0].exerciseTime, //运动时间
			// silenceHeartRate: data.list[0].silenceHeartRate, //静息心率
			// utc: formatDatelx(data.list[0].utc) //测量时间
	
			if(this.data.kcalValue > 0) {
				console.log('jinlailema--------步数数据-----');
			const userInfo = wx.getStorageSync('userInfo')
			var that = this
			console.log(userInfo.id);
			wx.request({
				url: `https://api.leshiguang.com/api/step/v2.0/upload/uploadBandDeviceStep?api_sign=${this.data.sign}&api_appKey=${this.data.appKeys}&api_version=1.0&api_timestamp=${this.data.timestamp}`,
				method: 'POST', // 请求方法为POST
				data: {
					// "associatedId": userInfo.id,
					// "list": [
					//   {
					// 	"calories": this.data.kcalValue, //卡路里
					// 	"deviceId": "38041300A53D",
					// 	"distance": this.data.distance, //距离米
					// 	"measurementTime": this.data.utc,  //测量时间
					// 	"step": this.data.step  //步数
					//   }
					// ]
					"associatedId": userInfo.id,
                    "list": [
                      {
                        "calories": that.data.kcalValue,
                        "deviceId": that.data.lzDeviceId,
                        "distance": that.data.distance,
                        "measurementTime": utc*1000,
                        "step": that.data.step
                      }
                    ]

				},
				header: {
				 'associatedId': userInfo.id,
				  'content-type': 'application/json' // 设置请求头为JSON格式
				},
				success: function(res) {
				  // 请求成功的回调函数
				  console.log(userInfo.id);
				 
				},
				fail: function(res) {
				  // 请求失败的回调函数
				  console.log(res.errMsg);
				}
			  });
			}
			
		},
		// 心率数据上传
		xinlvpush(utc, result,num){
			console.log('jinlailema--------心率上传-----',result);
			console.log(result.toString(16));
			var that = this
			const userInfo = wx.getStorageSync('userInfo')
			wx.request({
				url: `https://api.leshiguang.com/api/heartrate/v2.0/upload/uploadHeartRate?api_sign=${this.data.sign}&api_appKey=${this.data.appKeys}&api_version=1.0&api_timestamp=${this.data.timestamp}`,
				method: 'POST', // 请求方法为POST
				data: {
					"associatedId": userInfo.id,
					"list": [
					  {
						"deviceId":that.data.lzDeviceId,
						"heartRates": result.toString(16),
						"measurementDate": utc*1000, //测量时间
						"quantityOfHeartRate": num //测量长度
					  }
					]
	
				},
				header: {
				 'associatedId': userInfo.id,
				  'content-type': 'application/json' // 设置请求头为JSON格式
				},
				success: function(res) {
					console.log('心率上传成功--------------');
				  // 请求成功的回调函数
				  console.log(userInfo.id);
				},
				fail: function(res) {
				  // 请求失败的回调函数
				  console.log(res.errMsg);
				}
			  });
		},
		// 睡眠数据上传
		shuimianpush(list){
			var that = this
			console.log('jinlailema--------睡眠数据上传-----',this.data.appKeys);
			const userInfo = wx.getStorageSync('userInfo')
			wx.request({
				url: `https://api.leshiguang.com/api/sleep/v1.0/sleep/analysis/result/upload?api_sign=${this.data.sign}&api_appKey=${this.data.appKeys}&api_version=1.0&api_timestamp=${this.data.timestamp}`,
				method: 'POST', // 请求方法为POST
				data: list,
				header: {
				 'associatedId': userInfo.id,
				  'content-type': 'application/json' // 设置请求头为JSON格式
				},
				success: function(res) {
				  // 请求成功的回调函数
				  console.log(userInfo.id);
				 
				},
				fail: function(res) {
				  // 请求失败的回调函数
				  console.log(res.errMsg);
				}
			  });
		},
	// 链接设备
	goBindEq() {
		// if(!this.data.bleAvaible) {
		// 	wx.showToast({
		// 		title: '蓝牙初始化失败',
		// 		icon: 'none',
		// 		duration: 2000
		// 	})
		// 	return
		// }
		// this.setData({
		// 	bindDeviceTextInfo: '正在搜索手环设备'
		// })
		// this.setData({
		// 	showDialog: true
		// })
		// this.onScan()
		// this.createTimeInter()
		wx.navigateTo({
			url: '/sportsAdministration/pages/device/index'
		});
	},

	/**
   * 生命周期函数--监听页面隐藏
   */
	onHide() { },

	/**
   * 生命周期函数--监听页面卸载
   */
	onUnload() {
		clearInterval(this.data.timer)
		this.doDeleteMonitorDevice()
		wx.offBluetoothAdapterStateChange()	
	},

	/**
   * 页面相关事件处理函数--监听用户下拉动作
   */
	onPullDownRefresh() { },

	/**
   * 页面上拉触底事件的处理函数
   */
	onReachBottom() { },

	/**
   * 用户点击右上角分享
   */
	onShareAppMessage() { }
});
